let base64js = require('./base64js')
let Hex = require('./hex')
let SM4 = require('./sm4')

function SM4Util() {}

/**
 * sm4 ecb 加密
 * @param utf8Str
 * @param utf8Key
 */
SM4Util.sm4ECBEncrypt = function (utf8Str, utf8Key) {
  if (!utf8Key) {
    utf8Key = 'zzfh!@#$QazxWsxc'
  }
  let sm4 = new SM4()
  let keyBytes = Hex.utf8StrToBytes(utf8Key)
  let contentBytes = Hex.utf8StrToBytes(utf8Str)
  let cipher = sm4.encrypt_ecb(keyBytes, contentBytes)
  return base64js.fromByteArray(cipher)
}

/**
 * sm4 ecb 解密
 * @param utf8Str
 * @param utf8Key
 */
SM4Util.sm4ECBDecrypt = function (base64Str, utf8Key) {
  if (!utf8Key) {
    utf8Key = 'zzfh!@#$QazxWsxc'
  }
  let sm4 = new SM4()
  let keyBytes = Hex.utf8StrToBytes(utf8Key)
  let contentBytes = base64js.toByteArray(base64Str)
  let plain = sm4.decrypt_ecb(keyBytes, contentBytes)
  return Hex.bytesToUtf8Str(plain)
}

/**
 * sm4 cbc 加密
 * @param utf8Str
 * @param utf8Key
 * @param utf8Iv
 */
SM4Util.sm4CBCEncrypt = function (utf8Str, utf8Key, utf8Iv) {
  if (!utf8Key) {
    utf8Key = 'cmbtest1cmbtest1'
  }
  if (!utf8Iv) {
    utf8Iv = 'cmbtest1cmbtest1'
  }
  let sm4 = new SM4()
  let keyBytes = Hex.utf8StrToBytes(utf8Key)
  let ivBytes = Hex.utf8StrToBytes(utf8Iv)
  let contentBytes = Hex.utf8StrToBytes(utf8Str)
  let cipher = sm4.encrypt_cbc(keyBytes, ivBytes, contentBytes)
  return base64js.fromByteArray(cipher)
}

/**
 * sm4 cbc 解密
 * @param utf8Str
 * @param utf8Key
 * @param utf8Iv
 */
SM4Util.sm4CBCDecrypt = function (base64Str, utf8Key, utf8Iv) {
  if (!utf8Key) {
    utf8Key = 'cmbtest1cmbtest1'
  }
  if (!utf8Iv) {
    utf8Iv = 'cmbtest1cmbtest1'
  }
  let sm4 = new SM4()
  let keyBytes = Hex.utf8StrToBytes(utf8Key)
  let ivBytes = Hex.utf8StrToBytes(utf8Iv)
  let contentBytes = base64js.toByteArray(base64Str)
  let plain = sm4.decrypt_cbc(keyBytes, ivBytes, contentBytes)
  return Hex.bytesToUtf8Str(plain)
}

module.exports = SM4Util
